package cn.cboard.dao.sql;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import cn.cboard.dao.ThreadDao;
import cn.cboard.database.Query;
import cn.cboard.database.JdbcBuilder;
import cn.cboard.model.ForumThread;

public class ThreadDaoSql implements ThreadDao{
	private final static Logger logger = Logger.getLogger(ThreadDaoSql.class);
	private Query query;

	public ThreadDaoSql(Query query) {
		this.query = query;
	}
	

	public Collection<ForumThread> listThreads(Long forumId, Integer start,
			Integer count) {		
		logger.debug("[boadmx]-->list thread");
		String sqlquery = "select * from forumthreads where forumID=? order by threadid desc";
		List queryParams = new ArrayList();
		queryParams.add(forumId);	
		List list = new ArrayList();		
		try {
			list = query.queryMapper(queryParams, sqlquery, new ThreadMapper(), start, count);
		} catch (Exception e) {
			logger.error(e);
		}
		return list;
	}

	public ForumThread getThread(Long threadid) {
		logger.debug("[boardmx]--> getThread()");
		String sqlquery = "select * from forumthreads where threadID=?";
		List queryParams = new ArrayList();
		queryParams.add(threadid);
		
		ForumThread forumThread = new ForumThread();		
		try {
			 forumThread = (ForumThread) query.queryMapper(queryParams, sqlquery, new ThreadMapper());
		} catch (Exception e) {
			logger.error(e);
		}
		
		return forumThread;
	}

	public void createThread(ForumThread forumThread) {
		String sqlquery = "insert into forumthreads(forumid,roottopicid,title) value(?,?,?)";
		
		List queryParams = new ArrayList();		
		queryParams.add(forumThread.getForumId());
		queryParams.add(forumThread.getThreadId());
		queryParams.add(forumThread.getTitle());
		
		try {
			query.queryExecute(queryParams, sqlquery);
		} catch (Exception e) {
			logger.error(e);
		}
	}


	public void removeThread(Long threadId) {
		String sqlquery="delete forumthreads where threadid=?";
		List queryParams = new ArrayList();
		queryParams.add(threadId);
		
		try {
			query.queryExecute(queryParams, sqlquery);
		} catch (Exception e) {
			logger.error(e);
		}		
	}


	public void updateThread(ForumThread forumThread) throws Exception {
		String sqlquery = "update forumthreads set title=? where threadid=?";
		List queryParams = new ArrayList();
		queryParams.add(forumThread.getTitle());
		queryParams.add(forumThread.getThreadId());		
		query.queryExecute(queryParams, sqlquery);
	}
}
